package com.gcb.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONArray;
import com.gcb.common.exception.ServiceException;
import com.gcb.domain.dto.BusinessesQueryDTO;
import com.gcb.domain.dto.BusinessesSaveDTO;
import com.gcb.domain.entity.Businesses;
import com.gcb.domain.entity.Wharf;
import com.gcb.domain.vo.BusinessesVO;
import com.gcb.mapper.BusinessesMapper;
import com.gcb.service.IBusinessesService;
import com.gcb.service.IRegionService;
import com.gcb.service.IWharfService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class BusinessesServiceImpl implements IBusinessesService {

    @Resource
    private BusinessesMapper businessesMapper;
    @Resource
    private IWharfService wharfService;

    @Resource
    private IRegionService regionService;

    @Override
    public void add(BusinessesSaveDTO dto, Long currentUserId) {
        Businesses businesses = new Businesses();
        BeanUtil.copyProperties(dto, businesses);
        businesses.setCreateBy(currentUserId);
        businesses.setUpdateBy(currentUserId);
        businessesMapper.insert(businesses);
    }

    @Override
    public void delete(Long id) {
        List<Wharf> wharfList = wharfService.getByBusinessesId(id);
        if (wharfList != null && !wharfList.isEmpty()) {
            log.error("当前商户有关联数据，无法删除！");
            throw new ServiceException("当前商户有关联数据，无法删除！");
        }
        businessesMapper.delete(id);
    }

    @Override
    public void update(BusinessesSaveDTO dto, Long currentUserId) {
        Businesses businesses = new Businesses();
        BeanUtil.copyProperties(dto, businesses);
        businesses.setUpdateBy(currentUserId);
        businessesMapper.updateById(businesses);
    }

    @Override
    public List<BusinessesVO> list(BusinessesQueryDTO dto) {
        List<BusinessesVO> businessesVOS = businessesMapper.selectList(dto);
        businessesVOS.forEach(businessesVO -> {
            JSONArray cityCode = regionService.getCityCode(businessesVO.getCity());
            businessesVO.setCityCode(cityCode);
        });
        return businessesVOS;
    }
}
